import React, { useEffect } from 'react';
import { Gantt, Task, ViewMode } from 'gantt-task-react';
import { getStartEndDateForProject, initTasks } from './helper.tsx';
import { ViewSwitcher } from './view-switcher.tsx';
import 'gantt-task-react/dist/index.css';
import axiosInstance from '../request/axios.ts';

const GanttChart = (props: { fresh: number }) => {
  const [view, setView] = React.useState<ViewMode>(ViewMode.Year);

  const [tasks, setTasks] = React.useState<Task[]>(initTasks());

  const [isChecked, setIsChecked] = React.useState(true);

  useEffect(() => {
    axiosInstance.get(import.meta.env.VITE_HOST + '/getGantt').then(res => {
      // console.log(res);
      const data = res.data.data;
      // console.log(data);
      const tasks = data.map((task: Task) => {
        task.dependencies = task.dependencies || [];
        task.start = new Date(task.start);
        task.end = new Date(task.end);
        // task.id = task.id?.toString();
        // task.project = task.project?.toString();
        // task.dependencies = task.dependencies.map((item: number, idx: number) => {
        //   return task.dependencies[idx] = item.toString();
        // });
        return task;
      });
      setTasks(tasks);
    }).catch(error => {
      console.log(error);
      setTasks(initTasks());
    });
  }, [props.fresh]);

  let columnWidth = 65;
  if (view === ViewMode.Year) {
    columnWidth = 350;
  } else if (view === ViewMode.Month) {
    columnWidth = 300;
  } else if (view === ViewMode.Week) {
    columnWidth = 250;
  }

  const handleTaskChange = (task: Task) => {
    console.log('On date change Id:' + task.id);
    let newTasks = tasks.map(t => (t.id === task.id ? task : t));
    if (task.project) {
      const [start, end] = getStartEndDateForProject(newTasks, task.project);
      const project = newTasks[newTasks.findIndex(t => t.id === task.project)];
      if (
        project.start.getTime() !== start.getTime() ||
        project.end.getTime() !== end.getTime()
      ) {
        const changedProject = { ...project, start, end };
        newTasks = newTasks.map(t =>
          t.id === task.project ? changedProject : t,
        );
      }
    }
    setTasks(newTasks);
  };

  const handleTaskDelete = (task: Task) => {
    const conf = window.confirm('Are you sure about ' + task.name + ' ?');
    if (conf) {
      setTasks(tasks.filter(t => t.id !== task.id));
    }
    return conf;
  };

  const handleProgressChange = async (task: Task) => {
    setTasks(tasks.map(t => (t.id === task.id ? task : t)));
    console.log('On progress change Id:' + task.id);
  };

  const handleDblClick = (task: Task) => {
    alert('On Double Click event Id:' + task.id);
  };

  const handleClick = (task: Task) => {
    console.log('On Click event Id:' + task.id);
  };

  const handleSelect = (task: Task, isSelected: boolean) => {
    console.log(task.name + ' has ' + (isSelected ? 'selected' : 'unselected'));
  };

  const handleExpanderClick = (task: Task) => {
    setTasks(tasks.map(t => (t.id === task.id ? task : t)));
    console.log('On expander click Id:' + task.id);
  };

  return (
    <div className="Wrapper">
      <ViewSwitcher
        onViewModeChange={viewMode => setView(viewMode)}
        onViewListChange={setIsChecked}
        isChecked={isChecked}
      />
      <Gantt
        tasks={tasks}
        viewMode={view}
        locale="zh"
        onDateChange={handleTaskChange}
        onDelete={handleTaskDelete}
        onProgressChange={handleProgressChange}
        onDoubleClick={handleDblClick}
        onClick={handleClick}
        onSelect={handleSelect}
        onExpanderClick={handleExpanderClick}
        listCellWidth={isChecked ? '155px' : ''}
        columnWidth={columnWidth}
      />
    </div>
  );


};

export default GanttChart;